package com.jcli.jb51_net.article._198500_基于TCP协议网络socket编程;

import javax.swing.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 单线程
 */
public class TCPServerWithGUIOne extends JFrame {
    private JTextArea logTextArea;
    private JButton startButton;
    private JButton stopButton;
    private JTextField ipField;
    private JTextField portField;
    private JTextField messageField;
    private JButton sendButton;

    private ServerSocket serverSocket;
    private Socket clientSocket;
    private BufferedReader reader;
    private PrintWriter writer;

    private static final int DEFAULT_PORT = 8008;

    public TCPServerWithGUIOne() {
        setTitle("TCP 服务端");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 400);
        setLocationRelativeTo(null);

        JPanel topPanel = new JPanel(new FlowLayout());
        JPanel centerPanel = new JPanel(new BorderLayout());
        JPanel bottomPanel = new JPanel(new FlowLayout());

        startButton = new JButton("启动服务");
        stopButton = new JButton("停止服务");
        stopButton.setEnabled(false);

        ipField = new JTextField("127.0.0.1", 20);
        portField = new JTextField(String.valueOf(DEFAULT_PORT), 5);
        messageField = new JTextField(20);
        sendButton = new JButton("发送");

        topPanel.add(new JLabel("IP:"));
        topPanel.add(ipField);
        topPanel.add(new JLabel("端口:"));
        topPanel.add(portField);
        topPanel.add(startButton);
        topPanel.add(stopButton);

        logTextArea = new JTextArea();
        logTextArea.setEditable(false);

        JScrollPane scrollPane = new JScrollPane(logTextArea);
        centerPanel.add(scrollPane, BorderLayout.CENTER);

        bottomPanel.add(new JLabel("发送消息:"));
        bottomPanel.add(messageField);
        bottomPanel.add(sendButton);

        add(topPanel, BorderLayout.NORTH);
        add(centerPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.SOUTH);

        startButton.addActionListener(e -> startServer());
        stopButton.addActionListener(e -> stopServer());
        sendButton.addActionListener(e -> sendMessage());

        setVisible(true);
    }

    private void startServer() {
        SwingWorker<Void, String> worker = new SwingWorker<Void, String>() {
            @Override
            protected Void doInBackground() {
                try {
                    String ip = ipField.getText();
                    int port = Integer.parseInt(portField.getText());

                    serverSocket = new ServerSocket(port, 50, InetAddress.getByName(ip));
                    publish("服务器启动监听在" + ip + ":" + port + "端口...");
                    clientSocket = serverSocket.accept();

                    reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "utf-8"));
                    writer = new PrintWriter(clientSocket.getOutputStream(), true);

                    publish("新连接建立：" + clientSocket.getInetAddress());

                    String msg;
                    while ((msg = reader.readLine()) != null) {
                        publish("客户端消息：" + msg);
                        writer.println("服务器消息：" + msg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void process(java.util.List<String> chunks) {
                for (String message : chunks) {
                    logTextArea.append(message + "\n");
                }
            }
        };

        startButton.setEnabled(false);
        stopButton.setEnabled(true);
        worker.execute();
    }

    private void stopServer() {
        try {
            if (clientSocket != null && !clientSocket.isClosed()) {
                clientSocket.close();
            }
            if (serverSocket != null && !serverSocket.isClosed()) {
                serverSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        startButton.setEnabled(true);
        stopButton.setEnabled(false);
        logTextArea.append("服务器已停止\n");
    }

    private void sendMessage() {
        String message = messageField.getText();
        if (writer != null && clientSocket != null && clientSocket.isConnected()) {
            writer.println("服务器消息：" + message);
            logTextArea.append("服务器发送消息：" + message + "\n");
        } else {
            logTextArea.append("连接未建立或已断开\n");
        }
        messageField.setText("");
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TCPServerWithGUIOne::new);
    }
}
